/*
 * Copyright (c) 2023-2023 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.common.swagger.config;

import java.util.Map;
import java.util.Optional;
import org.elsfs.cloud.common.swagger.annotation.EnableSwaggerDoc;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

/**
 * openapi 配置类
 *
 * @author zeng
 */
public class OpenAPIDefinitionImportSelector implements ImportBeanDefinitionRegistrar {

  /**
   * 注册Bean定义方法
   *
   * @param metadata 注解元数据
   * @param registry Bean定义注册器
   */
  @Override
  public void registerBeanDefinitions(
      AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
    Optional<Map<String, Object>> map =
        Optional.ofNullable(
            metadata.getAnnotationAttributes(EnableSwaggerDoc.class.getName(), true));
    map.map(attrs -> attrs.get("value")).ifPresent(value -> createBeanDefinition(registry, value));
  }

  /**
   * 创建Bean定义
   *
   * @param registry Bean定义注册器
   * @param path Bean属性值
   */
  private void createBeanDefinition(BeanDefinitionRegistry registry, Object path) {
    BeanDefinitionBuilder beanDefinition =
        BeanDefinitionBuilder.genericBeanDefinition(OpenAPIDefinition.class);
    beanDefinition.addPropertyValue("path", path);
    registry.registerBeanDefinition("openAPIDefinition", beanDefinition.getBeanDefinition());
  }
}
